//
//  FKBannerView.m
//  FKBannerViewDemo
//
//  Created by 云眼科技 on 16/7/22.
//  Copyright © 2016年 CloudEyes. All rights reserved.
//

#import "FKBannerView.h"

static NSString *const bannerCellIdentifier = @"FKBannerCellIdentifier";

@interface FKBannerView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *myCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;


@end


@implementation FKBannerView

-(void)commonInit{
    _placeHolderImage = nil;
    _timeInterval = 2.f;
    _hidePageControl = NO;
    _indicatorColor = [UIColor whiteColor];
    _currentIndicatorColor = [UIColor grayColor];
    [self addSubview:self.myCollectionView];
    [self addSubview:self.pageControl];
}


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _style = FKBannerViewStyleDefault;
        [self commonInit];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame style:(FKBannerViewStyle)style{
    self = [super initWithFrame:frame];
    if (self) {
        _style = style;
        [self commonInit];
    }
    return self;
}


-(void)layoutSubviews{
    [super layoutSubviews];
    self.myCollectionView.frame = self.bounds;
    self.pageControl.frame = CGRectMake(0, self.frame.size.height - 20.f, self.frame.size.width, 20.f);
}


#pragma mark collectionView delegate & datasource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.datasource && [self.datasource respondsToSelector:@selector(numberOfItemsInBannerView:)]) {
        self.pageControl.numberOfPages = [self.datasource numberOfItemsInBannerView:self];
        return [self.datasource numberOfItemsInBannerView:self] == 0 ? 1 : [self.datasource numberOfItemsInBannerView:self];
    }else{
        return 0;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:bannerCellIdentifier forIndexPath:indexPath];
    if ([self.datasource numberOfItemsInBannerView:self] != 0) {
        
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        UIView *view = [self.datasource bannerView:self viewForItemAtIndex:indexPath.row];
        view.frame = cell.contentView.bounds;
        [cell.contentView addSubview:view];
    }else{
        UIImageView *placeImageView = [[UIImageView alloc] initWithFrame:cell.contentView.bounds];
        if (self.placeHolderImage) {
            placeImageView.image = self.placeHolderImage;
        }else{
            placeImageView.backgroundColor = [UIColor lightGrayColor];
        }
        [cell.contentView addSubview:placeImageView];
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(bannerView:didSelectedItemAtIndex:)]){
        NSInteger index = indexPath.row % [self.datasource numberOfItemsInBannerView:self];
        [self.delegate bannerView:self didSelectedItemAtIndex:index];
    }
}


-(void)addTimer{
    [self.timer invalidate];
    self.timer = nil;
    float time = _timeInterval == 0.0 ? 4.0 : _timeInterval;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}
- (void)nextPage{
    NSInteger itemCount = [self.datasource numberOfItemsInBannerView:self];
    if (itemCount == 0 || itemCount == 1) return;
    
    NSIndexPath *currentIndexPath = [[self.myCollectionView indexPathsForVisibleItems] firstObject];
    NSUInteger currentItem = currentIndexPath.item;
    NSUInteger nextItem = (currentItem + 1) % [self.datasource numberOfItemsInBannerView:self];

//    if (nextItem == 0) {
//        [self.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextItem inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
//    }else{
        [self.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextItem inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
//    }
}


- (void)removeTimer{
    [self.timer invalidate];
    self.timer = nil;
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    [self addTimer];
}

#pragma mark - scrollView delegate

//when collectionView content offset has been changed, change the pageControl's current page.
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.datasource == nil) return;
    int page = (int)(scrollView.contentOffset.x / scrollView.bounds.size.width + 0.5) % [self.datasource numberOfItemsInBannerView:self];
    self.pageControl.currentPage = page;
}


-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
    
    NSInteger currentItem = (NSInteger)(scrollView.contentOffset.x / self.frame.size.width);
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
    
//    UICollectionViewCell *cell = [self.myCollectionView cellForItemAtIndexPath:indexPath];
    
    [self.myCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
}

-(void)reloadData{
    [self.myCollectionView reloadData];
    if ([self.datasource numberOfItemsInBannerView:self] != 0) {
        [self.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        [self addTimer];
    }
}

#pragma mark - setters & getters

-(void)setStyle:(FKBannerViewStyle)style{
    _style = style;
}



-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _dataArray;
}

-(void)setPlaceHolderImage:(UIImage *)placeHolderImage{
    _placeHolderImage = placeHolderImage;

}

-(void)setIndicatorColor:(UIColor *)indicatorColor{
    _indicatorColor = indicatorColor;
    self.pageControl.pageIndicatorTintColor = indicatorColor;
}

-(void)setCurrentIndicatorColor:(UIColor *)currentIndicatorColor{
    _currentIndicatorColor = currentIndicatorColor;
    self.pageControl.currentPageIndicatorTintColor = currentIndicatorColor;
}

-(void)setTimeInterval:(NSTimeInterval)timeInterval{
    _timeInterval = timeInterval;
    [self addTimer];
}


-(UICollectionViewFlowLayout *)layout{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _layout.itemSize = self.bounds.size;
        _layout.minimumLineSpacing = 0;
        _layout.minimumInteritemSpacing = 0;
        
    }
    return _layout;
}

-(UICollectionView *)myCollectionView{
    if (!_myCollectionView) {
        _myCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout];
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
        _myCollectionView.pagingEnabled = YES;
        _myCollectionView.backgroundColor = [UIColor whiteColor];
        _myCollectionView.showsVerticalScrollIndicator = NO;
        _myCollectionView.showsHorizontalScrollIndicator = NO;
        _myCollectionView.bounces = NO;
        [_myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:bannerCellIdentifier];
    }
    return _myCollectionView;
}


-(UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.pageIndicatorTintColor = self.indicatorColor;
        _pageControl.currentPageIndicatorTintColor = self.currentIndicatorColor;
        _pageControl.currentPage = 0;
    }
    return _pageControl;
}

@end
